local tair_manager = require "ngx.tair"

-- return tair server
local function get_tair()
    local group = ngx.var.tair_group
    if not group then
        ngx.log(ngx.ERR, "[tair rest]tair_group not set, please use 'set $tair_group groupname' in config")
        return nil
    end

    local tair,msg = tair_manager:init(group)
    if not tair then
        ngx.log(ngx.ERR, "[tair rest]tair group not found ", group)
        return nil
    end

    return tair
end

local function do_get(namespace, key)

    local tair = get_tair()

    if not tair then
       return
    end

    key = string.format("%s_%d", key, ngx.time()%10)

    local request = {["data"] = {{["key"] = key, ["ktype"] = "untype"}}}
    local res,code,msg = tair:mget(tonumber(namespace), request)

    if code == 0 and res.data[1] then
        if res.data[1].code == 0 then
           return
        elseif res.data[1].code == 1 or res.data[1].code == -3998 then
            -- notfound
           ngx.exec("@punish");
        end
    end

    -- error
    return
end

local function process()

   local namespace = ngx.var["tair_namespace"]
   local key = ngx.var["cookie_cookie17"]

   if not key then
        ngx.exec("@login")
   end

    do_get(namespace, key)

end

process()
